package com.szrca.ima.response;

import javax.servlet.http.HttpServletResponse;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

public class ResponseAsJsonHandler implements HandlerMethodReturnValueHandler{

	private HttpMessageConverter<Object> messageConverter=new MappingJackson2HttpMessageConverter();	
	
	
	public ResponseAsJsonHandler(HttpMessageConverter<Object> messageConverter){
		this.messageConverter=messageConverter;
	}
	
	@Override
	public boolean supportsReturnType(MethodParameter returnType) {
		Class<?> paramType=returnType.getParameterType();
		
		return paramType.getPackage().isAnnotationPresent(ResponseAsJson.class)
				|| returnType.getMethod().isAnnotationPresent(ResponseAsJson.class)
				|| paramType.isAnnotationPresent(ResponseAsJson.class);
	}

	@Override
	public void handleReturnValue(Object returnValue,
			MethodParameter returnType, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest) throws Exception {
		mavContainer.setRequestHandled(true);
		ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(webRequest.getNativeResponse(HttpServletResponse.class));
		messageConverter.write(returnValue, MediaType.APPLICATION_JSON, outputMessage);
	}

}
